const jwt = require('../Lib/Jwt')
// 定义跳过验证的中间件
const escape = [
    '/v1/authorize'
]
module.exports = async function (ctx, next) {
    // 跳过不需要签名的接口
    let url = ctx.request.url
    if (escape.includes(url)) {
        return next()
    }
    const authorization = ctx.req.headers.Authorization || ctx.req.headers.authorization
    const bearer = /^Bearer .+/
    if ( !bearer.test( authorization ) ) ctx.throw('Token 格式不配备', 200)
    const token = authorization.replace( /^Bearer /, '' )
    
    let decode = await jwt.verify(token)
    if (decode) {
        let time = Date.now()
        let iat = decode.iat     //创建时间
        let exp = decode.exp * 1000     // 有效期
    
        // 判断token 过期
        if (time > exp) ctx.throw('Token 已过期')
        
        ctx.user = decode.user   //用户信息 包含用户名 用户id
        ctx.token = token        //jwt
        ctx.token_info = decode  //完整的解码信息
    } else {
        ctx.throw('非法Token')
    }
   
    return next()
}